package cn.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import entity.User;

public class CookieFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		Cookie[] cookies = request.getCookies();
		User user = null;
		boolean sign = false;
		Map<String, String> info = new HashMap<String, String>();
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				info.put(cookie.getName(), cookie.getValue());
				if (cookie.getName().equals("user")) {
					sign = true;
				}
			}

		}
		if (sign) {
			user = new User(info.get("user"), info.get("upwd"));
			request.getSession().setAttribute("user", user);
		}
		arg2.doFilter(request, arg1);

	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
